<?php
namespace  Ekadmin\Controller;

use \Think\Controller;

use Think\Page;

use Vendor\Tree;



class ActivityController extends CommonController

{


        /**
         *@活动正常或者冻结操作
         *para参数说明：
         *1表示活动正在进行，2表示冻结，活动下架
         */
        public function setStatus()

        {

            if(IS_POST){

                $goods = M('activity')->where("id=".I("id")." and uniacid=".$this->uniacid)->find();

                $save['status'] = $goods['status'] == 1 ?  2:1;

                $save['id'] = I('id');
                
                $save["uniacid"]=$this->uniacid;
                
                if($save['status']==1){  //表示正常，2表示冻结
                    M('activity')->where("id!=".$save['id']." and uniacid=".$this->uniacid)->setField("status",2);
                }                

                M('activity')->save($save);

                ajax_return(0,'操作成功');

            }

        }
        
        /**
         *@活动是否可使用优惠卷操作
         */
        public function setCoupon(){
            if(IS_POST){
            
                $goods = M('activity')->where("id=".I("id")." and uniacid=".$this->uniacid)->find();
            
                $save['is_coupon'] = $goods['is_coupon'] == 1 ?  2:1;
            
                $save['id'] = I('id');
                
                $save["uniacid"]=$this->uniacid;
            
                M('activity')->save($save);
            
                ajax_return(0,'操作成功');
            
            }
        }
        
        /**
         *@活动置顶或者取消置顶操作 
         */
        public function setHome(){
            if(IS_POST){
            
                $goods = M('activity')->where("id=".I("id")." and uniacid=".$this->uniacid)->find();
            
                $save['is_home'] = $goods['is_home'] == 1 ?  2:1;
            
                $save['id'] = I('id');
                
                $save["uniacid"]=$this->uniacid;
            
                M('activity')->save($save);
            
                ajax_return(0,'操作成功');
            
            }
        }
        
        

        /**
         *@显示活动列表 
         */
        public  function index()

        {

            $where="uniacid= ".$this->uniacid." ";
            $status=isset($_REQUEST['status'])?intval($_REQUEST['status']):0;
            $id=isset($_REQUEST['id'])?intval($_REQUEST['id']):0;
            $name=isset($_REQUEST['name'])?trim($_REQUEST['name']):'';
            $periods=isset($_REQUEST['periods'])?trim($_REQUEST['periods']):'';
            
            if($status){
                $where.=" and status=".$status;
            }
            if($id){
                $where.=" and id=".$id;
            }
            if(!empty($name)){
                $where.=" and name like '%".$name."%'";
            }
            if(!empty($periods)){
                $where.=" and periods='".$periods."'";
            }
            $obj = M('activity');

            $count = $obj->where($where)->count();

            $page = new Page($count);

            $list = $obj->where($where)->limit($page->firstRow.','.$page->listRows)->order("id desc")->select();
            
            for($i=0;$i<count($list);$i++){
                if($list[$i]["is_limit_xiaoqu"]==2){
                    $str="";
                    $rs=M("xiaoqu")->field("id,name")->where("id in (".$list[$i]["allow_xiaoqu_ids"].") and uniacid=".$this->uniacid)->select();
                    if($rs){
                        for($j=0;$j<count($rs);$j++){
                            $str.=$rs[$j]["name"].",";
                        }
                        $list[$i]["allow_xiaoqu_ids"]=substr($str,0,-1);
                    }
                    
                }else{
                    $list[$i]["allow_xiaoqu_ids"]="不限";
                }
            }
            $this->assign('page',$page->show());

            $this->assign('count',$count);

            $this->assign('list',$list);

            $this->display();

        }




        /**
         *@显示活动修改页面 
         */
        public function  edit()

        {

            $data = M('activity')->where("id=".I("id")." and uniacid=".$this->uniacid)->find();

            $imgs = explode('|',$data['ad_imgs']);

            $this->assign('flag',C('upload_type'));

            $this->assign('url',U("Upload/saveimg_kind"));

            $this->assign('data',$data);

            $this->assign('imgs',$imgs);

            $this->display('form');

        }




        /**
         *@活动入库显示页面 
         */
        public function add()

        {

            $this->display('form');

        }
        /**
         *@活动修改提交操作 
         */
        public function update()

        {
            if(IS_POST){

                $param = I('post.');

//                 if(!$param['header']){

//                     ajax_return(1,'请上传发起者头像');

//                 }
                if(!$param['periods']){
                
                    ajax_return(1,'团购期数不能为空');
                
                }               
                if(!$param['name']){
                
                    ajax_return(1,'活动标题不能为空');
                
                }                
                if(!$param['desc']){
                
                    ajax_return(1,'活动描述不能为空');
                
                }
                
//                 if(!$param['nickname']){
                
//                     ajax_return(1,'发起者昵称不能为空');
                
//                 }               
                
//                 if(!$param['mobile']){
                
//                     ajax_return(1,'活动电话不能为空');
                
//                 }                
                
                $param['start_time'] = strtotime($param['start_time']);
                
                $param['end_time'] = strtotime($param['end_time']);

                $param['tihuo_start_time'] = strtotime($param['tihuo_start_time']);
                
                $param['tihuo_end_time'] = strtotime($param['tihuo_end_time']);
                
//                 if(count($param['summary_imgs'])<1){

//                     ajax_return(1,'请上传媒体信息');

//                 }




//                 $param['ad_imgs'] = implode('|',$param['summary_imgs']);

//                 unset($param['summary_imgs']);
                

              //  $param['desc'] = str_replace('/addons/yb_fxyx/','https://'.$_SERVER['SERVER_NAME'].'/addons/yb_fxyx/',$param['desc']);



                $obj = M('activity');

                if($param['id']){
                    
                    if($param['status']==1){  //表示正常，2表示冻结
                        $obj->where("id!=".$param["id"]." and uniacid=".$this->uniacid)->setField("status",2);
                    }

                    $param['updatetime'] = time();

                    $obj->save($param);

                }else{

                    $param['addtime'] = time();

                    $param['uniacid'] = $this->uniacid;
                    
                    if($param["status"]==1){
                        M('activity')->where("1=1")->setField("status",2);
                    }

                    $obj->add($param);

                }

                ajax_return(0,'保存成功',U('index'));

            }

        }





        private function addAttr($attr=[])

        {

            $arr=[];

            foreach ($attr as $k =>$v)

            {

                $arr_item =[

                  'attr_list'=>[],

                  'price'=>doubleval($v['price']),

                  'num' =>intval($v['num'])

                ];



                foreach ($v['attr_list'] as $kk => $vv)

                {



                    $attrgroup = M('attr_group')->where(['attr_group_name'=>$vv['attr_group_name']])->find();



                    $id = $attrgroup['id'];

                    if(!$attrgroup){



                        $add['uniacid'] = $this->acid;

                        $add['attr_group_name'] = $vv['attr_group_name'];

                        $add['addtime'] = time();



                        $id = M('attr_group')->add($add);

                    }



                    $attr = M('attr')->where(['attr_name'=>$vv['attr_name'],'attr_group_id'=>$id])->find();

                    $id2 = $attr['id'];

                    if(!$attr){

                        $add2['attr_group_id'] = $id;

                        $add2['attr_name'] = $vv['attr_name'];

                        $add2['addtime'] = time();

                        $id2 = M('attr')->add($add2);



                    }



                    $arr_item['attr_list'][]=[

                        'attr_id'=>$id2,

                        'attr_name' => $attr['attr_name'] ?$attr['attr_name']:$vv['attr_name']

                    ];



                }

                $arr[] = $arr_item;

            }



            return $arr;

        }





        public function attr()

        {

            if(IS_POST){

                $param = I('post.');

                if(!isset($param['attr'])){

                    $param['attr'] ='';

                }else{

                    $param['attr'] = json_encode($param['attr']);

                }

                M('goods')->save($param);

                ajax_return(0,'保存成功',U('index'));

            }else{

                $goods = M('goods')->find(I('get.id'));

                $this->assign('id',I('get.id'));

                $attr = json_decode($goods['attr'],true);

                $attrs=[];

                foreach ($attr as $k => $v)

                {

                    foreach ($v['attr_list'] as $kk => $vv)

                    {

                        $attrs[] = $vv['attr_id'];

                    }

                }


                $ag = M('attr_group')->select();

                foreach ($ag as $k => $v)

                {

                    $attrs2 = M('attr')->where(['attr_group_id'=>$v['id']])->select();

                    foreach ($attrs2 as $kk => $vv)

                    {      $check = false;

                        if(in_array($vv['id'],$attrs)){

                            $check = true;

                        }

                        $attrs2[$kk]['checked']= $check;

                    }

                    $ag[$k]['children'] =$attrs2;

                }

                $this->assign('ag',$ag);

                $ag = M('attr_group')->select();

                $attrGroupList=[];

                foreach ($ag as $k1 => $v1)

                {

                    $item=[];

                    $item['attr_group_name'] = $v1['attr_group_name'];

                    $item['attr_group_id'] = $v1['id'];

                    $attrs21 = M('attr')->where(['attr_group_id'=>$v1['id']])->select();



                    if(!$attrs21){



                        continue;

                    }else{

                        foreach ($attrs21 as $kkk => $vvv)

                        {

                            $uu=[];

                            $uu['attr_name']=$vvv['attr_name'];

                            $uu['attr_id']=$vvv['id'];

                            $check = false;

                            if(in_array($vvv['id'],$attrs)){

                                $check = true;

                            }

                            $uu['checked'] = $check;

                            $item['attr_list'][] = $uu;

                        }

                    }

                    $attrGroupList[] = $item;

                }

                $this->assign('attrGroupList',$attrGroupList);

                $this->assign('checkedAttrList',$goods['attr']?$goods['attr']:'{}');

                $this->display();

            }

        }
    
    /**
     *@批量删除操作 
     */
    public function del()

    {

        if(IS_POST){

            $param = I('id');

            if(is_array($param)){

                $map['id'] = array('in',$param);

            }else{

                $map['id'] = $param;

            }
            
            $map["uniacid"]=$this->uniacid;

            M('activity')->where($map)->delete();

            ajax_return(0,'删除成功');

        }

    }

    /**
     *@批量冻结操作
     */
    public function isnotstatus(){
        if(IS_POST){
        
            $param = I('id');
        
            if(is_array($param)){
        
                $map['id'] = array('in',$param);
        
            }else{
        
                $map['id'] = $param;
        
            }
            
            $map["uniacid"]=$this->uniacid;
        
            M('activity')->where($map)->setField('status',2);
        
            ajax_return(0,'冻结操作成功');
        
        }        
    }

    /**
     *@批量上线操作
     */
    public function isstatus(){
        if(IS_POST){
    
            $param = I('id');
    
            if(is_array($param)){
    
                $map['id'] = array('in',$param);
    
            }else{
    
                $map['id'] = $param;
    
            }
            
            $map["uniacid"]=$this->uniacid;
    
            M('activity')->where($map)->setField('status',1);
    
            ajax_return(0,'上线操作成功');
    
        }
    }
    
    /**
     *@显示添加商品列表 
     */
    public function goods(){
        if(!isset($_GET['id']) || intval($_GET["id"])<=0){
            ajax_return(1, '参数不正确');
        }

        
        $id=intval($_GET['id']);
        $this->pid=$id;
        $arr=array(
            "uniacid"=>$this->uniacid,
            "id"=>$id
        );
        $ob=M('activity')->where($arr)->find();
        $str=$ob['id'].'.<font color="red"><strong>当前活动：'.$ob['name']."</strong></font>";
        $this->assign("str",$str);
        $goods_ids=explode(',', $ob['goods_ids']);
        $allow_xiaoqu_ids=explode(',', $ob['allow_xiaoqu_ids']);
        $this->assign("allow_xiaoqu_ids",$allow_xiaoqu_ids);
        $this->assign("goods_ids",$goods_ids);
        
        //读取商品分类
        $map["uniacid"]=$this->uniacid;
        $this->info=M("goodsclass")->where($map)->field('id ,name')->order('id desc')->select();
        
        $classid=isset($_GET["classid"])? intval($_GET["classid"]):0;
        $name=isset($_GET["name"])? trim($_GET["name"]):'';
        
        $where=' is_del=1 and is_shangjia=1 and uniacid='.$this->uniacid;        
        if($classid){
            $where.=" and classid=".$classid;
        }
        if($name!=""){
            $where.=" and name like '%".$name."%'";
        }
        
        $obj = M('goods');
        
        $count = $obj->where($where)->count();
        
        $page = new Page($count);
        
        $list = $obj->field("id,name,is_shangjia")->where($where)->limit($page->firstRow.','.$page->listRows)->order("id desc")->select();

        $this->assign('page',$page->show());
        
        $this->assign('count',$count);
        
        $this->assign('list',$list);
        
        $this->display('goods');
    }
    
    /**
     *@添加活动商品 
     */
    public function addActivegoods(){
        if(!isset($_POST["id"]) || !isset($_POST["pid"])){
            ajax_return(1,'非法操作');
        }
        $id=I('id');
        $pid=I('pid');
        $rs=M("activity")->field('id,goods_ids')->where("id=".$pid." and uniacid=".$this->uniacid)->find();
        if($rs['goods_ids']!=""){
            $tmp=explode(",",$rs['goods_ids']);
            if(in_array($id, $tmp)){
                ajax_return(1, '商品已存在活动中，请刷新页面重试!');
            }
            $goods_ids=$rs['goods_ids'].",".$id;
        }else{
            $goods_ids=$id;
        }
        $arr=array(
            'goods_ids'=>$goods_ids
        );
        M("activity")->where("id=".$pid." and uniacid=".$this->uniacid)->setField($arr);
        
        ajax_return(0, '添加成功');
    }
    
    /**
     *@取消活动商品 
     */
    public function canelActivegoods(){
        if(!isset($_POST["id"]) || !isset($_POST["pid"])){
            ajax_return(1,'非法操作');
        }
        $id=I('id');
        $pid=I('pid');
        $rs=M("activity")->field('id,goods_ids')->where("id=".$pid." and uniacid=".$this->uniacid)->find();
        $goods_ids=explode(',',$rs['goods_ids']);
        
        $key = array_search($id, $goods_ids);
        if ($key !== false)
            array_splice($goods_ids, $key, 1);        
        if(count($goods_ids)>0){
            $str=implode(',', $goods_ids);
            $arr=array(
                'goods_ids'=>$str
            );
        }else{
            $arr=array(
                'goods_ids'=>''
            );
        }
        M("activity")->where("id=".$pid." and uniacid=".$this->uniacid)->setField($arr);
        
        ajax_return(0, '删除成功');
    }
    
    /**
     *@显示添加小区列表 
     */
    public function xiaoqu(){
        if(!isset($_GET['id']) || intval($_GET["id"])<=0){
            ajax_return(1, '参数不正确');
        }
        
        $id=intval($_GET['id']);
        $this->pid=$id;
        $ob=M('activity')->where("uniacid=".$this->uniacid." and id=".$id)->find();
        $str=$ob['id'].'.<font color="red"><strong>当前活动：'.$ob['name']."</strong></font>";
        $this->assign("str",$str);
        $goods_ids=explode(',', $ob['goods_ids']);
        $allow_xiaoqu_ids=explode(',', $ob['allow_xiaoqu_ids']);
        $this->assign("allow_xiaoqu_ids",$allow_xiaoqu_ids);
        
        //读取商品分类
        $this->info=M("quyu")->field('id ,name')->where("uniacid=".$this->uniacid)->order('sort desc')->select();
        
        $quyu_id=isset($_GET["quyu_id"])? intval($_GET["quyu_id"]):0;
        $name=isset($_GET["name"])? trim($_GET["name"]):'';
        
        $where=' status=1 and uniacid='.$this->uniacid;
        if($quyu_id){
            $where.=" and quyu_id=".$quyu_id;
        }
        if($name!=""){
            $where.=" and name like '%".$name."%'";
        }
        
        $obj = M('xiaoqu');
        
        $count = $obj->where($where)->count();
        
        $page = new Page($count);
        
        $list = $obj->field("id,name")->where($where)->limit($page->firstRow.','.$page->listRows)->order("id desc")->select();
        
        $this->assign('page',$page->show());
        
        $this->assign('count',$count);
        
        $this->assign('list',$list);
        
        $this->display('xiaoqu');
    }
    
    
    /**
     *@添加活动小区操作
     */
    public function addActivexiaoqu(){
        if(!isset($_POST["id"]) || !isset($_POST["pid"])){
            ajax_return(1,'非法操作');
        }
        $id=I('id');
        $pid=I('pid');
        $rs=M("activity")->field('id,allow_xiaoqu_ids')->where(" uniacid=".$this->uniacid." and id=".$pid)->find();
        if($rs['allow_xiaoqu_ids']!=""){
            $tmp=explode(",",$rs['allow_xiaoqu_ids']);
            if(in_array($id, $tmp)){
                ajax_return(1, '小区已存在活动中，请刷新页面重试!');
            }
            $allow_xiaoqu_ids=$rs['allow_xiaoqu_ids'].",".$id;
        }else{
            $allow_xiaoqu_ids=$id;
        }
        $arr=array(
            'is_limit_xiaoqu'=>2,
            'allow_xiaoqu_ids'=>$allow_xiaoqu_ids
        );
        M("activity")->where("id=".$pid." and uniacid=".$this->uniacid)->setField($arr);
    
        ajax_return(0, '添加成功');
    }
    
    /**
     *@取消活动小区操作
     */
    public function canelActivexiaoqu(){
        if(!isset($_POST["id"]) || !isset($_POST["pid"])){
            ajax_return(1,'非法操作');
        }
        $id=I('id');
        $pid=I('pid');
        $rs=M("activity")->field('id,allow_xiaoqu_ids')->where(" id=".$pid." and uniacid=".$this->uniacid)->find();
        $allow_xiaoqu_ids=explode(',',$rs['allow_xiaoqu_ids']);
    
        $key = array_search($id, $allow_xiaoqu_ids);
        if ($key !== false)
            array_splice($allow_xiaoqu_ids, $key, 1);
            if(count($allow_xiaoqu_ids)>0){
                $str=implode(',', $allow_xiaoqu_ids);
                $arr=array(
                    'allow_xiaoqu_ids'=>$str
                );
            }else{
                $arr=array(
                    'is_limit_xiaoqu'=>1,
                    'allow_xiaoqu_ids'=>''
                );
            }
            M("activity")->where("id=".$pid." and uniacid=".$this->uniacid)->setField($arr);
    
            ajax_return(0, '删除成功');
    }
    
    /**
     *@快速复制活动 
     */
    public function copyActive(){
        $param = I('id');
        
        if(is_array($param)){
        
            $map['id'] = array('in',$param);
        
        }else{
        
            $map['id'] = $param;
        
        }
        
        $map["uniacid"]=$this->uniacid;
        
        $rs=M("activity")->where($map)->find();
        
        if(!$rs){
            ajax_return(1, '活动不存在');
        }
        
        unset($rs["id"],$rs["periods"]);
        
        $rs["status"]=2;
        
        $rs["periods"]=date("Ymd");
        
        M("activity")->data($rs)->add();
        
        ajax_return(0, "操作成功");
        
        
        
    }
    
}